/*
 * #%L
 * SwiftUICommonUtilities
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
package com.linkwithweb.products.swiftui.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileUtils {
	private static final transient Log logger = LogFactory
			.getLog(FileUtils.class);

	public static String readFile(String url) {
		StringBuffer msg = new StringBuffer();
		FileInputStream stream = null;
		DataInputStream in = null;
		BufferedReader br = null;
		String strLine;
		try {
			url = url.replaceAll("file:/", "").replaceAll("%20", " ");
			logger.debug("-----------------Trying to Read File at :" + url);
			stream = new FileInputStream(new File(url));
			// Get the object of DataInputStream
			in = new DataInputStream(stream);
			br = new BufferedReader(new InputStreamReader(in));

			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
				msg.append(strLine.trim());
			}
		} catch (Exception e) {
			logger.debug(e);
		} finally {
			// Close the input stream
			try {
				in.close();
				stream.close();
			} catch (IOException e) {
				logger.debug(e);
			}

		}
		return msg.toString();
	}

	/**
	 * @param stream
	 * @return
	 */
	public static String readFile(InputStream stream) {
		StringBuffer msg = new StringBuffer();
		DataInputStream in = null;
		BufferedReader br = null;
		String strLine;
		try {
			// Get the object of DataInputStream
			in = new DataInputStream(stream);
			br = new BufferedReader(new InputStreamReader(in));

			// Read File Line By Line
			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
				msg.append(strLine.trim());
			}
		} catch (Exception e) {
			logger.debug(e);
		} finally {
			// Close the input stream
			try {
				in.close();
				stream.close();
			} catch (IOException e) {
				logger.debug(e);
			}

		}
		return msg.toString();
	}
}
